package cn.xd.core.response;

import cn.hutool.core.util.ObjUtil;
import cn.xd.common.exception.BizException;
import cn.xd.core.exception.DBException;

import java.util.function.Consumer;

/**
 * @author : mirzaLin
 * @data : 2023/11/19
 * @description : DB单条数据结果
 **/
public class ObjectResult<T> {
    private final T res;

    private ObjectResult(T res) {
        this.res = res;
    }

    public static <T> ObjectResult<T> of(T t) {
        return new ObjectResult<>(t);
    }

    public T get() {
        return res;
    }

    public T isEmptyThrow(RuntimeException exception) throws RuntimeException {
        if (ObjUtil.isEmpty(res)) {
            throw exception;
        }
        return res;
    }

    public T isEmptyThrow(String msg) throws BizException {
        return isEmptyThrow(new BizException(msg));
    }

    public T isEmptyThrow() {
        return isEmptyThrow(new DBException("db异常"));
    }

    public T isEmpty(Function consumer) {
        if (ObjUtil.isEmpty(res)) {
            consumer.execute();
        }
        return res;
    }

    public T isNotEmptyThrow(RuntimeException exception) throws RuntimeException {
        if (ObjUtil.isNotEmpty(res)) {
            throw exception;
        }
        return res;
    }

    public T isNotEmptyThrow(String msg) throws BizException {
        return isNotEmptyThrow(new BizException(msg));
    }

    public T isNotEmpty(Consumer<T> consumer) {
        if (ObjUtil.isNotEmpty(res)) {
            consumer.accept(res);
        }
        return res;
    }


}
